package com.blobfish.fiction.common.pageprocessor;

import cn.hutool.core.lang.Console;
import com.blobfish.fiction.book.BookChapterService;
import com.blobfish.fiction.common.DemoConfig;
import com.blobfish.fiction.common.model._MappingKit;
import com.blobfish.fiction.common.pipeline.WujixiaoshuoPipeline;
import com.jfinal.aop.Aop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * 无极小说爬虫
 *
 * @author huangbo
 */
public class WujixiaoshuoPageProcessor implements PageProcessor {
    /**
     * 节点
     */
    private Site site = Site.me().setRetryTimes(10).setSleepTime(3000);
    static BookChapterService bookChapterService = Aop.get(BookChapterService.class);

    @Override
    public void process(Page page) {
        Console.log("{}下载完毕", page.getUrl());
        List<String> urlList = page.getHtml().links().regex("(https://m\\.wujixiaoshuo\\.com/\\w+/\\w+)").all();
        List<String> resultList = new ArrayList<>(urlList.size() * 2);
        urlList.forEach(item -> {
            bookChapterService.addUrl(item, resultList);
        });
        page.addTargetRequests(resultList);
        Console.log("添加下载任务:{}", resultList);
        page.putField("url", page.getUrl().toString());
        page.putField("title", page.getHtml().xpath("//header[@id=\"top\"]/span/text()").toString());
        page.putField("value", page.getHtml().xpath("//div[@id=\"chaptercontent\"]/tidyText()").toString());
    }

    @Override
    public Site getSite() {
        return site;
    }
}
